/**
 * 
 */
package com.laivi.basic.model;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Map;
import java.util.Properties;

import com.laivi.basic.module.log.Log;
import com.laivi.basic.module.log.Logs;

/**
 * @author laivi.zhu@gmail.com
 * @date 2014-7-5
 * description:
 */
public class Property {
	private final static Log log=Logs.getLog(Property.class);
	private Properties prop;
	
	private File file;

	public Property(String path) {
		//this(new File(Property.class.getResource(path).getPath()));
		prop=new Properties();
		try {
			prop.load(Property.class.getResourceAsStream(path));
		} catch (FileNotFoundException e) {
			log.error("file not found:"+e.getMessage());
		} catch (IOException e) {
			log.error(e.getMessage());
		}
	}
	
	public Property(File file){
		this.file=file;
		prop=new Properties();
		try {
			prop.load(new FileInputStream(this.file));
		} catch (FileNotFoundException e) {
			log.error("file not found:"+e.getMessage());
		} catch (IOException e) {
			log.error(e.getMessage());
		}
	}
	
	public String get(String key){
		return prop.getProperty(key);
	}
	
	public String get(String key,String defaultValue){
		return prop.getProperty(key, defaultValue);
	}
	
	public void add(String key,Object value){
		prop.put(key, value);
	}
	
	public void add(Map<String,Object> values){
		prop.putAll(values);
	}
	
	public void addAndSave(String key,String value){
		add(key,value);
		save("add the key:"+key);
	}
	
	public void addAndSave(Map<String,Object> values){
		add(values);
		save("add the many keys:"+values);
	}
	
	public void remove(String key){
		prop.remove(key);
	}
	
	public void removeAndSave(String key){
		remove(key);
		save("remove the key:"+key);
	}
	
	public void save(String commont){
		try {
			prop.store(new FileOutputStream(this.file), commont);
		} catch (FileNotFoundException e) {
			log.error("file not found:"+e.getMessage());
		} catch (IOException e) {
			log.error(e.getMessage());
		}
	}
}
